<template>
  <div>
    <el-card style="margin: 10px auto;height: 50%;">
      <template #header style="position:relative;">
        <span class="head">後台訂單</span>
        <el-button type="success" class="orderButton" @click="addOrder">提交訂單</el-button>
      </template>
      <template>
        <el-form ref="form" :model="orderParam" label-width="130px" :rules="rules">
          <el-row>
            <el-col :span="8">
              <el-form-item label="訂單綁定賬號" prop="memberId">
                <el-select
                  v-model="orderParam.memberId"
                  filterable
                  remote
                  :loading="userLoading"
                  :remote-method="remoteGetUser"
                  placeholder="请选择用戶"
                  clearable
                >
                  <el-option
                    v-for="item in list"
                    :key="item.id"
                    :label="item.username"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="訂單備註" prop="buyerMemo">
                <el-input v-model="orderParam.buyerMemo" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="結款方式" prop="settlementType">
                <el-select
                  v-model="orderParam.settlementType"
                  placeholder="请选择結款方式"
                >
                  <el-option
                    v-for="item in dict.settlementType"
                    :key="item.id"
                    :label="item.dictValue"
                    :value="item.dictKey"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-col :span="8">
            <el-form-item label="支付方式">
              {{ dict.label.payType[orderParam.payType[0]] }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收貨人姓名" prop="receiverName">
              <el-input v-model="orderParam.receiverName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="聯繫方式" prop="receiverPhone">
              <el-input v-model="orderParam.receiverPhone" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="派送方式" prop="deliveryType">
              <el-select
                v-model="orderParam.deliveryType"
                placeholder="選擇商品后解鎖"
                clearable
                :disabled="orderParam.orderItems.length < 1"
                @change="clearDeliveryTime"
              >
                <el-option
                  v-for="item in dict.deliveryType"
                  :key="item.id"
                  :label="item.dictValue"
                  :value="item.dictKey"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收貨地址區域" prop="receiverRegionId">
              <el-select
                v-model="orderParam.receiverRegionId"
                placeholder="请选择收貨地址區域"
                clearable
                :disabled="orderParam.deliveryType === null"
                @change="getBuild"
              >
                <el-option
                  v-for="item in region"
                  :key="item.id"
                  :label="item.nameCn"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="派送時間">
              <el-cascader
                placeholder="请选择派送時間"
                :options="deliveryTime"
                clearable
                :props="{label:'label',value:'label'}"
                :disabled="orderParam.receiverRegionId === null"
                @change="selTime"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="!orderParam.deliveryType" :span="8">
            <el-form-item label="收貨樓宇名稱">
              <el-select
                v-model="orderParam.receiverBuildingId"
                placeholder="请选择收貨樓宇名稱"
                clearable
                filterable
                remote
                :loading="userLoading"
                @change="getBuildName"
              >
                <el-option
                  v-for="item in receiverBuilding"
                  :key="item.id"
                  :label="item.nameCn"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="!orderParam.deliveryType" :span="8">
            <el-form-item label="收貨地址街道名">
              <el-input v-model="orderParam.receiverStreet" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收貨單位" prop="receiverDetailAddress">
              <el-input v-model="orderParam.receiverDetailAddress" />
            </el-form-item>
          </el-col>
        </el-form>
      </template>
    </el-card>
    <el-card style="margin: 10px auto;height: 50%;">
      <template #header style="position:relative;">
        <span class="head">商品列表</span>
        <el-button
          v-permission="['admin', 'addOfflineOrder:editPrice']"
          class="editButton"
          type="warning"
          :disabled="orderParam.orderItems.length < 1"
          @click="clickChangePrice = !clickChangePrice"
        >編輯價格
        </el-button>
        <el-button class="orderButton" type="primary" @click="openProduct">新增商品</el-button>
      </template>
      <template>
        <el-table
          ref="productTable"
          :data="orderParam.orderItems"
          style="width: 100%"
          stripe
          row-key="sku"
        >
          <el-table-column
            label="商品名稱"
            width="400px"
          >
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column
            label="商品編碼"
          >
            <template slot-scope="scope">
              {{ scope.row.sku }}
            </template>
          </el-table-column>
          <el-table-column
            prop="price"
            label="價格"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.price"
                size="mini"
                style="width: 120px"
                :disabled="clickChangePrice"
                @input="calculatePrice"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="productQuantity"
            label="數量"
          >
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.productQuantity"
                size="mini"
                :precision="0"
                :min="1"
                @change="calculatePrice"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="金額"
            align="right"
          >
            <template slot-scope="scope">
              {{ (scope.row.price * scope.row.productQuantity).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            align="right"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click.native.prevent="deleteRow(scope.$index, orderParam.orderItems)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <p class="totalRow">
          合計金額：${{ orderParam.payAmount || 0 }}
        </p>
      </template>
    </el-card>
    <product ref="product" @childNotify="selectProduct" />

  </div>
</template>

<script>
import { add } from '@/api/oms/order'
import { getAll } from '@/api/oms/orderRegion'
import { getDeliveryTimeAll } from '@/api/sms/mallSet'
import { page } from '@/api/ums/member'

const defaultOrderMessage = {
  createTime: null,
  freightAmount: null,
  receiverName: null,
  receiverPhone: null,
  receiverRegion: null,
  receiverRegionId: null,
  receiverBuildingId: null,
  receiverBuilding: null,
  receiverStreet: null,
  receiverDetailAddress: null,
  orderItems: [],
  payAmount: null,
  manualOrder: true,
  buyerMemo: null,
  deliveryType: null,
  payType: ['cod'],
  deliveryDate: null,
  timeSlot: null,
  settlementType: null
}
import product from '@/components/product'

export default {
  name: 'AddOfflineOrder',
  components: { product },
  dicts: ['deliveryType', 'payType', 'settlementType'],
  data() {
    return {
      dialogVisible: false,
      orderParam: Object.assign({}, defaultOrderMessage),
      userList: [],
      list: [],
      userLoading: false,
      region: [],
      receiverBuilding: [],
      productIds: [],
      deliveryTime: [],
      clickChangePrice: true,
      rules: {
        memberId: [
          { required: true, message: '請選擇賬號', trigger: 'change' }
        ],
        buyerMemo: [
          { required: true, message: '請填寫備註', trigger: 'blur' }
        ],
        settlementType: [
          { required: true, message: '請選擇結款方式', trigger: 'change' }
        ],
        receiverName: [
          { required: true, message: '請填寫收貨人姓名', trigger: 'blur' }
        ],
        receiverPhone: [
          { required: true, message: '請填寫聯繫方式', trigger: 'blur' }
        ],
        deliveryType: [
          { required: true, message: '請選擇配送方式', trigger: 'change' }
        ],
        receiverRegionId: [
          { required: true, message: '請選擇收貨地址區域', trigger: 'change' }
        ],
        receiverDetailAddress: [
          { required: true, message: '請填寫具體單位', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRegionAll(0)
  },
  methods: {
    openProduct() {
      this.dialogVisible = true
      this.$refs.product.open()
    },
    remoteGetUser(query) {
      if (query !== '') {
        this.loading = true
        page({ memberName: query, size: 50 }).then(res => {
          if (res.code === 0) {
            this.loading = false
            this.list = res.data.rows
          }
        })
      } else {
        this.list = []
      }
    },
    addOrder() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          add(this.orderParam).then(res => {
            if (res.code === 0) {
              this.$notify({
                title: '成功',
                message: res.message,
                type: 'success'
              })
              this.$router.back()
            } else {
              this.$notify({
                title: '失敗',
                message: res.message,
                type: 'error'
              })
            }
          })
        }
      })
    },
    selectProduct(params) {
      if (params.length === 0) {
        this.$message.error('请选择商品')
      } else {
        const productIdArr = this.orderParam.orderItems.map(item => {
          return item.productId
        })
        for (const item of params) {
          if (!productIdArr.includes(item.product.id)) {
            this.productIds.push(item.product.id)
            this.orderParam.orderItems.push({
              productId: item.product.id,
              price: item.product.originalPrice,
              productQuantity: 1,
              name: item.product.nameCn,
              sku: item.product.sku,
              amount: (item.product.originalPrice * 1).toFixed(2)
            })
          }
        }
        this.$refs.product.close()
        this.$refs.product.refresh()
        this.calculatePrice()
      }
    },
    deleteRow(index, rows) {
      rows.splice(index, 1)
      this.calculatePrice()
    },
    calculatePrice(params) {
      let payAmount = null
      this.orderParam.orderItems.forEach(item => {
        payAmount = ((Number(item.price) * Number(item.productQuantity)) + Number(payAmount))
      })
      this.orderParam.payAmount = Number(payAmount).toFixed(2)
    },
    getRegionAll(regionId) {
      getAll({ parentId: regionId }).then(res => {
        if (res.code === 0) {
          if (regionId === 0) {
            this.region = res.data
          } else {
            this.receiverBuilding = res.data
          }
        }
      })
    },
    getBuild(sel) {
      this.getRegionAll(sel)
      getDeliveryTimeAll(
        { deliveryType: this.orderParam.deliveryType, regionId: sel, productIds: this.productIds }).then(res => {
        const times = res.data
        if (res.code === 0) {
          for (const key in times) {
            const KeyItem = times[key].map(item => {
              return { label: item }
            })

            this.deliveryTime.push({ label: key, children: KeyItem })
          }
        }
        this.getRegion(sel)
      })
    },
    clearDeliveryTime() {
      this.deliveryTime = []
      this.orderParam.receiverRegionId = null
      this.orderParam.deliveryDate = null
      this.orderParam.timeSlot = null
      if (this.orderParam.orderItems.length < 1) {
        this.$message({
          message: '請先選擇商品',
          type: 'warning'
        })
      }
    },
    selTime(sel) {
      this.orderParam.deliveryDate = `${sel[0]} 00:00:00`
      this.orderParam.timeSlot = sel[1]
    },
    getRegion(sel) {
      this.region.forEach(item => {
        if (item.id === sel) {
          this.orderParam.receiverRegion = item.nameCn
        }
      })
    },
    getBuildName(sel) {
      this.receiverBuilding.forEach(item => {
        if (item.id === sel) {
          this.orderParam.receiverBuilding = item.nameCn
        }
      })
    }
  }
}
</script>

<style scoped>
.head {
  font-weight: bolder;
  font-size: 26px;
}

.orderButton {
  position: absolute;
  right: 5%;
}

.editButton {
  position: absolute;
  right: 15%;
}
.totalRow {
  text-align: right;
  color: gray;
}
</style>
